<!--
 * @Description: 登录组件
 -->
<template>
  <div id="myLogin">
    <el-dialog title="登录" width="300px" center :visible.sync="isLogin">
      <el-form
        :model="LoginUser"
        :rules="rules"
        status-icon
        ref="ruleForm"
        class="demo-ruleForm"
      >
        <el-form-item prop="username">
          <el-input
            prefix-icon="el-icon-user-solid"
            placeholder="请输入账号"
            v-model="LoginUser.username"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            prefix-icon="el-icon-view"
            type="password"
            maxlength="6"
            placeholder="请输入密码"
            v-model="LoginUser.password"
          ></el-input>
        </el-form-item>
        <el-form-item prop="code">
          <el-input
            style="width: 120px; float: left"
            prefix-icon="el-icon-umbrella"
            placeholder="验证码"
            maxlength="5"
            v-model="LoginUser.code"
          ></el-input>
          <el-image
            :src="captchaImg"
            class="captchaImg"
            @click="getcaptchaImg"
          ></el-image>
        </el-form-item>
        <el-form-item>
          <el-button
            size="medium"
            type="primary"
            @click="Login"
            style="width: 100%"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { mapActions } from "vuex";
import qs from "qs";

export default {
  name: "MyLogin",
  data() {
    // 用户名的校验方法
    let validateName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入用户名"));
      }
      // 用户名以字母开头,长度在5-16之间,允许字母数字下划线
      const userNameRule = /[a-zA-Z0-9_]{0,19}$/;
      if (userNameRule.test(value)) {
        this.$refs.ruleForm.validateField("checkPass");
        return callback();
      } else {
        return callback(new Error("字母开头,长度5-16之间,允许字母数字下划线"));
      }
    };
    // 密码的校验方法
    let validatePass = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("请输入密码"));
      }
      // 密码以字母开头,长度在4-18之间,允许字母数字和下划线
      // const passwordRule = /^[a-zA-Z]\w{3,17}$/;
      // if (passwordRule.test(value)) {
      //   this.$refs.ruleForm.validateField("checkPass");
      //   return callback();
      // } else {
      //   return callback(
      //     new Error("字母开头,长度6-18之间,允许字母数字和下划线")
      //   );
      // }
      return callback();
    };
    let validateCode = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("请输入验证码"));
      }
      return callback();
    };
    return {
      LoginUser: {
        username: "1",
        password: "1",
        code: "",
        token: "",
      },
      captchaImg: "",
      // 用户信息校验规则,validator(校验方法),trigger(触发方式),blur为在组件 Input 失去焦点时触发
      rules: {
        username: [{ validator: validateName, trigger: "blur" }],
        password: [{ validator: validatePass, trigger: "blur" }],
        code: [{ validator: validateCode, trigger: "blur" }],
      },
    };
  },
  computed: {
    // 获取vuex中的showLogin，控制登录组件是否显示
    isLogin: {
      get() {
        return this.$store.getters.getShowLogin;
      },
      set(val) {
        this.$refs["ruleForm"].resetFields();
        this.setShowLogin(val);
      },
    },
  },
  created() {
    this.getcaptchaImg();
  },
  methods: {
    ...mapActions(["setUser", "setShowLogin", "getUser"]),
    getcaptchaImg() {
      this.$axios.get("/captcha").then((res) => {
        // 待优化
        console.log(res.data.data.captchaImg);
        this.LoginUser.token = res.data.data.token;
        this.captchaImg = res.data.data.captchaImg;
      });
    },
    Login() {
      // 通过element自定义表单校验规则，校验用户输入的用户信息
      this.$refs["ruleForm"].validate((valid) => {
        //如果通过校验开始登录
        if (valid) {
          this.$axios
            .post("/login?" + qs.stringify(this.LoginUser))
            .then((res) => {
              // 200代表登录成功，其他的均为失败
              if (res.data.code === 200) {
                // 隐藏登录组件
                this.isLogin = false;
                // 登录信息存到本地 用户名 "用户名"
                let user = JSON.stringify(res.data.data.user);
                // let user = res.data.data.user
                localStorage.setItem("user", user);
                // 登录信息存到vuex
                localStorage.setItem("user", user);
                this.setUser(res.data.data.user);
                // 弹出通知框提示登录成功信息
                this.notifySucceed(res.data.data.msg);
              } else {
                // 清空输入框的校验状态
                this.$refs["ruleForm"].resetFields();
                // 弹出通知框提示登录失败信息
                this.notifyError(res.data.msg);
              }
            })
            .catch((err) => {
              return Promise.reject(err);
            });
        } else {
          return false;
        }
      });
    },
  },
};
</script>
<style scoped>
.captchaImg {
  float: left;
  margin-left: 8px;
  border-radius: 4px;
}
</style>>
